﻿using Demo_test.Models.Entity;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using PagedList;
using System.Web.Mvc;
using System.Web.UI.WebControls;

namespace Demo_test.Controllers
{
    public class UserController : BaseController
    {
        // GET: User
        Model1 db = new Model1();
        [HttpGet]
        public ActionResult Insert()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Insert(Username model)
        {
           
            try
            {
                db.Usernames.Add(model);
                db.SaveChanges();
                ModelState.AddModelError("", "Cập nhật thành công !");
               
                SetAlert("Thêm User thanh công" ,"success");
                return RedirectToAction("Index");
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("", ex.Message);             

                return View("Index", model);

            }

        }
        

       

        public ActionResult Edit(int id)
        {

            var model = db.Usernames.Find(id);            
            return View(model);
        }
        [HttpPost]
        public ActionResult Edit(Username model)
        {
            try
            {
                db.Entry(model).State = EntityState.Modified;
                db.SaveChanges();
                SetAlert("Sửa User thanh công", "success");

                ModelState.AddModelError("", "Cập nhật Thành Công");

            }
            catch (Exception ex)
            {
                ModelState.AddModelError("", ex.Message);

            }
           
            return RedirectToAction("Index", model);
        }
        public ActionResult Delete(int Id)
        {
            var model = db.Usernames.Find(Id);
            db.Usernames.Remove(model);
            db.SaveChanges();
            SetAlert("xóa User thanh công", "success");
            return RedirectToAction("Index");
        }


        [HttpGet]
        public ActionResult Index(int page =1 ,int pageSize = 4)
        {
           
            List<Username> ListUername = db.Usernames.ToList();
            PagedList<Username> model = new PagedList<Username>(ListUername, page, pageSize);
            return View(model);
        }
        [HttpPost]
        public ActionResult Index(FormCollection formCollection)
        {
            string[] ids = formCollection["productId"].Split(new char[] { ',' });
            foreach (string id in ids)
            {
                var product = db.Usernames.Find(int.Parse(id));
                db.Usernames.Remove(product);
                db.SaveChanges();
            }
           
            return RedirectToAction("Index");
        }
       

    }
}